package com.bridgeintelligent.tag.webserver.schedule.service.imp;

import com.bridgeintelligent.tag.webserver.schedule.api.IQualityService;
import com.bridgeintelligent.tag.webserver.schedule.api.pojo.DimFree;
import com.bridgeintelligent.tag.webserver.schedule.api.pojo.DimFreeQuality;
import com.bridgeintelligent.tag.webserver.schedule.service.mapper.DimFreeQualityMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * @description
 * @author: grp 2020-09-14 11:26
 **/
@Service
@AllArgsConstructor
@Slf4j
public class QualityServiceImpl implements IQualityService {
    DimFreeQualityMapper dimFreeQualityMapper;
    @Override
    public void update(String date) {
        // 获取总人数
        Long total = dimFreeQualityMapper.countTotal(date);
        if(total==null||total==0){
            log.warn("通过etl获取的客户总人数为0");
            return;
        }
        // 清理
        dimFreeQualityMapper.clearQuality();
        // 遍历
        List<DimFree> dimFrees = dimFreeQualityMapper.findDimFree();
        if(CollectionUtils.isEmpty(dimFrees)){
            log.warn("不存在自定义标签");
            return;
        }
        for(DimFree dimFree:dimFrees){
            try {
                getQuality(dimFree, date, total);
            }catch (Exception e){
                log.error("获取标签质量出错", e);
            }
        }
    }

    private void getQuality(DimFree dimFree, String date, long total) throws IOException {
        // 计算
        if(StringUtils.isBlank(dimFree.getCustList())){
            log.warn("用户列表为空：{}",dimFree.getDimId());
            return;
        }
        long lines = Files.lines(Paths.get(new File(dimFree.getCustList()).getPath())).count();
        DimFreeQuality quality = new DimFreeQuality();
        BigDecimal bhd = new BigDecimal(lines).divide(new BigDecimal(total),4,BigDecimal.ROUND_HALF_UP);

        quality.setColName(dimFree.getDimId()).setTotal(lines).setYcPercent("0%")
                .setKzPercent((1-bhd.doubleValue())*100+"%")
                .setBhdPercent(bhd.doubleValue()*100+"%")
                .setUpdateDate(date).setTagType(dimFree.getClassify());
        dimFreeQualityMapper.save(quality);
    }
}
